<template>
  <div class="material-detail-container">
    <div class="material-header">
      <div class="back-link">
        <router-link to="/materials">
          <i class="el-icon-arrow-left"></i> 返回资料列表
        </router-link>
      </div>
      
      <div class="material-title-section">
        <h1 class="material-title">{{ material.title }}</h1>
        <div class="material-meta">
          <span class="material-type">{{ getTypeText(material.type) }}</span>
          <span class="material-size">{{ formatSize(material.size) }}</span>
          <span class="upload-time">上传时间：{{ formatDate(material.uploadTime) }}</span>
          <span class="view-count"><i class="el-icon-view"></i> {{ material.viewCount }}</span>
          <span class="download-count"><i class="el-icon-download"></i> {{ material.downloadCount }}</span>
        </div>
      </div>
    </div>
    
    <el-card class="material-content">
      <div class="material-info-section">
        <div class="material-description">
          <h3>资料简介</h3>
          <p>{{ material.description }}</p>
        </div>
        
        <div class="material-tags">
          <h3>标签</h3>
          <div class="tags-list">
            <el-tag v-for="tag in material.tags" :key="tag" size="small" effect="plain">{{ tag }}</el-tag>
          </div>
        </div>
        
        <div class="material-related">
          <h3>相关课程</h3>
          <ul class="related-courses">
            <li v-for="(course, index) in material.relatedCourses" :key="index">
              <router-link :to="`/course/${course.id}`">{{ course.title }}</router-link>
            </li>
          </ul>
        </div>
      </div>
      
      <div class="material-preview-section">
        <h3>资料预览</h3>
        
        <div v-if="material.type === 'document'" class="document-preview">
          <iframe :src="material.previewUrl" width="100%" height="600"></iframe>
        </div>
        <div v-else-if="material.type === 'video'" class="video-preview">
          <video controls width="100%">
            <source :src="material.previewUrl" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
        </div>
        <div v-else-if="material.type === 'audio'" class="audio-preview">
          <audio controls style="width: 100%">
            <source :src="material.previewUrl" type="audio/mpeg">
            您的浏览器不支持音频播放
          </audio>
        </div>
        <div v-else class="other-preview">
          <el-empty description="无法预览该类型资料，请下载后查看"></el-empty>
        </div>
      </div>
      
      <div class="material-actions">
        <el-button type="primary" size="medium" @click="downloadMaterial">
          <i class="el-icon-download"></i> 下载资料
        </el-button>
        <el-button type="success" size="medium" @click="collectMaterial">
          <i :class="material.collected ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
          {{ material.collected ? '已收藏' : '收藏' }}
        </el-button>
        <el-button type="info" size="medium" @click="shareMaterial">
          <i class="el-icon-share"></i> 分享
        </el-button>
      </div>
    </el-card>
    
    <el-card class="material-comments">
      <div class="comments-header">
        <h3>学习笔记与讨论</h3>
        <el-button type="primary" size="small" @click="showCommentDialog">添加笔记</el-button>
      </div>
      
      <div v-if="comments.length === 0" class="no-comments">
        <el-empty description="暂无笔记，快来添加第一条吧！"></el-empty>
      </div>
      
      <div v-else class="comments-list">
        <div v-for="(comment, index) in comments" :key="index" class="comment-item">
          <div class="comment-user">
            <el-avatar :size="40" :src="comment.avatar"></el-avatar>
            <div class="comment-info">
              <div class="comment-name">{{ comment.username }}</div>
              <div class="comment-time">{{ formatDate(comment.createTime) }}</div>
            </div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions">
            <span class="action-item" @click="likeComment(comment)">
              <i :class="comment.liked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
              {{ comment.likes }} 赞
            </span>
            <span class="action-item" @click="replyComment(comment)">
              <i class="el-icon-chat-dot-round"></i> 回复
            </span>
          </div>
          
          <!-- 回复列表 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
            <div v-for="(reply, rIndex) in comment.replies" :key="rIndex" class="reply-item">
              <div class="reply-user">
                <el-avatar :size="30" :src="reply.avatar"></el-avatar>
                <div class="reply-info">
                  <div class="reply-name">{{ reply.username }}</div>
                  <div class="reply-time">{{ formatDate(reply.createTime) }}</div>
                </div>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 添加笔记对话框 -->
    <el-dialog
      title="添加学习笔记"
      :visible.sync="commentDialogVisible"
      width="50%"
    >
      <el-form :model="commentForm" :rules="commentRules" ref="commentForm">
        <el-form-item label="笔记内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入您的学习笔记或讨论内容"
            v-model="commentForm.content"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交</el-button>
      </span>
    </el-dialog>
    
    <!-- 分享对话框 -->
    <el-dialog
      title="分享资料"
      :visible.sync="shareDialogVisible"
      width="40%"
    >
      <div class="share-options">
        <div class="share-item" @click="shareVia('wechat')">
          <i class="share-icon wechat-icon"></i>
          <span>微信</span>
        </div>
        <div class="share-item" @click="shareVia('weibo')">
          <i class="share-icon weibo-icon"></i>
          <span>微博</span>
        </div>
        <div class="share-item" @click="shareVia('qq')">
          <i class="share-icon qq-icon"></i>
          <span>QQ</span>
        </div>
        <div class="share-item" @click="shareVia('link')">
          <i class="el-icon-link"></i>
          <span>复制链接</span>
        </div>
      </div>
      <div class="share-link">
        <el-input v-model="shareLink" readonly>
          <el-button slot="append" @click="copyLink">复制</el-button>
        </el-input>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'MaterialDetail',
  data() {
    return {
      material: {
        id: '',
        title: '',
        description: '',
        type: '',
        size: 0,
        uploadTime: '',
        viewCount: 0,
        downloadCount: 0,
        previewUrl: '',
        url: '',
        tags: [],
        relatedCourses: [],
        collected: false
      },
      comments: [],
      commentDialogVisible: false,
      commentForm: {
        content: ''
      },
      commentRules: {
        content: [
          { required: true, message: '请输入笔记内容', trigger: 'blur' },
          { min: 5, message: '内容至少 5 个字符', trigger: 'blur' }
        ]
      },
      shareDialogVisible: false,
      shareLink: ''
    }
  },
  created() {
    this.fetchMaterialDetail()
    this.fetchComments()
  },
  methods: {
    ...mapActions(['getMaterialDetail', 'getMaterialComments', 'addMaterialComment', 'collectMaterial']),
    async fetchMaterialDetail() {
      try {
        const id = this.$route.params.id
        const data = await this.getMaterialDetail(id)
        this.material = data
      } catch (error) {
        console.error('获取资料详情失败', error)
        this.$message.error('获取资料详情失败')
      }
    },
    async fetchComments() {
      try {
        const id = this.$route.params.id
        const data = await this.getMaterialComments(id)
        this.comments = data
      } catch (error) {
        console.error('获取评论失败', error)
      }
    },
    downloadMaterial() {
      // 实际项目中这里应该调用API进行下载
      window.open(this.material.url, '_blank')
      this.$message.success('资料下载中...')
    },
    async collectMaterial() {
      try {
        await this.collectMaterial({
          id: this.material.id,
          collected: !this.material.collected
        })
        this.material.collected = !this.material.collected
        this.$message.success(this.material.collected ? '收藏成功' : '已取消收藏')
      } catch (error) {
        console.error('操作失败', error)
        this.$message.error('操作失败')
      }
    },
    shareMaterial() {
      this.shareLink = `${window.location.origin}/material/${this.material.id}`
      this.shareDialogVisible = true
    },
    shareVia(platform) {
      // 实际项目中这里应该根据不同平台进行分享
      console.log(`分享到${platform}`, this.shareLink)
      this.$message.success(`已分享到${platform}`)
      this.shareDialogVisible = false
    },
    copyLink() {
      const input = document.createElement('input')
      input.value = this.shareLink
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('链接已复制到剪贴板')
    },
    showCommentDialog() {
      this.commentDialogVisible = true
    },
    submitComment() {
      this.$refs.commentForm.validate(async valid => {
        if (valid) {
          try {
            await this.addMaterialComment({
              materialId: this.material.id,
              content: this.commentForm.content
            })
            this.$message.success('添加笔记成功')
            this.commentDialogVisible = false
            this.commentForm.content = ''
            this.fetchComments() // 重新获取评论列表
          } catch (error) {
            console.error('添加笔记失败', error)
            this.$message.error('添加笔记失败')
          }
        }
      })
    },
    likeComment(comment) {
      // 实际项目中这里应该调用API进行点赞
      comment.liked = !comment.liked
      comment.likes += comment.liked ? 1 : -1
      this.$message.success(comment.liked ? '点赞成功' : '已取消点赞')
    },
    replyComment(comment) {
      this.$prompt('请输入回复内容', '回复', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputPattern: /.{5,}/,
        inputErrorMessage: '回复内容至少 5 个字符'
      }).then(({ value }) => {
        // 实际项目中这里应该调用API进行回复
        if (!comment.replies) {
          comment.replies = []
        }
        comment.replies.push({
          username: '当前用户',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          content: value,
          createTime: Date.now()
        })
        this.$message.success('回复成功')
      }).catch(() => {
        // 取消回复
      })
    },
    getTypeText(type) {
      const typeMap = {
        document: '文档',
        video: '视频',
        audio: '音频',
        other: '其他'
      }
      return typeMap[type] || '未知'
    },
    formatSize(size) {
      if (!size) return '0 KB'
      
      const units = ['B', 'KB', 'MB', 'GB']
      let i = 0
      while (size >= 1024 && i < units.length - 1) {
        size /= 1024
        i++
      }
      return Math.round(size * 100) / 100 + ' ' + units[i]
    },
    formatDate(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.material-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.material-header {
  margin-bottom: 20px;
  
  .back-link {
    margin-bottom: 15px;
    
    a {
      color: #606266;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      
      &:hover {
        color: #409EFF;
      }
      
      i {
        margin-right: 5px;
      }
    }
  }
  
  .material-title-section {
    .material-title {
      font-size: 24px;
      color: #303133;
      margin: 0 0 15px;
    }
    
    .material-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      color: #909399;
      font-size: 14px;
      
      .material-type {
        background-color: #ecf5ff;
        color: #409EFF;
        padding: 2px 8px;
        border-radius: 3px;
      }
    }
  }
}

.material-content {
  margin-bottom: 20px;
  
  .material-info-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 30px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
    
    h3 {
      font-size: 18px;
      color: #303133;
      margin: 0 0 10px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .material-description {
      grid-column: span 2;
      
      @media (max-width: 768px) {
        grid-column: span 1;
      }
      
      p {
        margin: 0;
        line-height: 1.6;
        color: #606266;
      }
    }
    
    .tags-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .related-courses {
      padding-left: 20px;
      margin: 0;
      
      li {
        margin-bottom: 8px;
        
        a {
          color: #409EFF;
          text-decoration: none;
          
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
  
  .material-preview-section {
    margin-bottom: 30px;
    
    h3 {
      font-size: 18px;
      color: #303133;
      margin: 0 0 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
    }
  }
  
  .material-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}

.material-comments {
  .comments-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      font-size: 18px;
      color: #303133;
      margin: 0;
    }
  }
  
  .no-comments {
    padding: 30px 0;
  }
  
  .comments-list {
    .comment-item {
      padding: 15px 0;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
    }
    
    .comment-user {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      
      .comment-info {
        margin-left: 10px;
      }
      
      .comment-name {
        font-weight: 500;
        color: #303133;
      }
      
      .comment-time {
        font-size: 12px;
        color: #909399;
        margin-top: 3px;
      }
    }
    
    .comment-content {
      margin-bottom: 10px;
      line-height: 1.6;
      color: #606266;
    }
    
    .comment-actions {
      display: flex;
      gap: 15px;
      
      .action-item {
        font-size: 14px;
        color: #909399;
        cursor: pointer;
        
        &:hover {
          color: #409EFF;
        }
        
        i {
          margin-right: 3px;
        }
      }
    }
    
    .reply-list {
      margin-top: 15px;
      margin-left: 50px;
      background-color: #f5f7fa;
      border-radius: 4px;
      padding: 10px;
      
      .reply-item {
        padding: 10px 0;
        border-bottom: 1px solid #ebeef5;
        
        &:last-child {
          border-bottom: none;
        }
      }
      
      .reply-user {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .reply-info {
          margin-left: 10px;
        }
        
        .reply-name {
          font-weight: 500;
          color: #303133;
          font-size: 14px;
        }
        
        .reply-time {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .reply-content {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.share-options {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  
  .share-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    
    i {
      font-size: 32px;
      margin-bottom: 8px;
    }
    
    .share-icon {
      width: 40px;
      height: 40px;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: center;
      margin-bottom: 8px;
    }
    
    .wechat-icon {
      background-color: #07c160;
      border-radius: 50%;
    }
    
    .weibo-icon {
      background-color: #e6162d;
      border-radius: 50%;
    }
    
    .qq-icon {
      background-color: #12b7f5;
      border-radius: 50%;
    }
  }
}

.share-link {
  margin-top: 20px;
}
</style> 